package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdLoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * 用户登陆
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdLoginDto dto) {

        // 校验参数
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 校验用户是否存在
        // 根据用户名称查询用户
        AdUser aduser = this.getOne(Wrappers.lambdaQuery(AdUser.class)
                .eq(AdUser::getName, dto.getName()));
        if (aduser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 判断密码是否正确
        String salt = aduser.getSalt();
        String password = dto.getPassword();

        String asHex = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!aduser.getPassword().equals(asHex)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        // 修改登陆时间
        aduser.setLoginTime(new Date());
        this.updateById(aduser);

        // 封装结果
        Map<String, Object> map = new HashMap<>();

        map.put("token", AppJwtUtil.getToken(aduser.getId().longValue()));

        aduser.setPassword("");
        aduser.setSalt("");
        map.put("user", aduser);

        return ResponseResult.okResult(map);
    }
}
